/*
 * Created on Nov 20, 2003
 *
 * To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package tools.phobius;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import tools.Jalview.Feature;


/**
 * @author cm	
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 *
 */

public class PhobiusParser {
	private BufferedReader reader;
	private boolean hasmoreseq= true;
	private PhobiusShortAlignment curralign= null;

	public PhobiusParser(BufferedReader reader) throws IOException, Exception {
		this.reader= reader;
		reader.readLine();
		readNext();
	}
	
	/* (non-Javadoc)
	 * @see java.util.Iterator#hasNext()
	 */
	public boolean hasNext() {
		return hasmoreseq;
	}

	/* (non-Javadoc)
	 * @see java.util.Iterator#next()
	 */
	public Object next() {
		try {
			return nextAlignment();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @deprecated
	 * @return
	 */
	public boolean hasMoreAlignments() {
		return hasmoreseq;
	}
	
	/**
	 * @deprecated
	 * @return
	 * @throws IOException
	 * @throws BioException
	 */
	public PhobiusShortAlignment nextAlignment() throws IOException, Exception {
		if (hasmoreseq == false) 
			throw new Exception("No more sequences");
		PhobiusShortAlignment tmp= curralign;
		readNext();
		
		return tmp;
	}
	
	private void readNext() throws IOException, Exception {
		String s= reader.readLine();
		if (s==null) {
			hasmoreseq= false;
		}
		else {
			String[] l= s.split(" +");
			if (l.length != 4) {
				throw new Exception("Invalid line: "+s);
			}
			
			PhobiusShortAlignment align= new PhobiusShortAlignment();
			align.id=l[0];
			align.TM=Integer.parseInt(l[1]);
			if (l[2].charAt(0)=='Y')
				align.SP=1;
			else
				align.SP=Integer.parseInt(l[2]);
			align.prediction=l[3];
			
			
			
			curralign = align;
			hasmoreseq= true;
		}
	}

	public static void main(String[] args) throws IOException, Exception {
		BufferedReader reader= new BufferedReader(new FileReader(args[0]));
		PhobiusParser parser= new PhobiusParser(reader);
		while (parser.hasMoreAlignments()) {
			PhobiusShortAlignment a= parser.nextAlignment();
			ArrayList<Feature> e=a.toJalviewTMFeature();
			for (Feature feature : a.toJalviewTMFeature()) {
				System.out.println(feature);
			}
//			System.out.println(a.toJalviewTMFeature());
		}
		
	}

	/* (non-Javadoc)
	 * @see java.util.Iterator#remove()
	 */
	public void remove() {
		throw new UnsupportedOperationException();
	}

}
